<?php

namespace common\exception;

use Exception;
use think\exception\Handle;
use think\facade\Log;

/*
 * 重写Handle的render方法，实现自定义异常消息
 */

class ExceptionHandler extends Handle
{
    /**
     * 渲染异常
     * @param Exception $e
     * @return \think\Response|\think\response\Json
     */
    public function render(Exception $e)
    {
        if ($e instanceof BaseException) {
            $exception_info = $e->getInfo();
        } else {
            $this->recordErrorLog($e);
            if (config('app_debug')) {
                echo "<p style='font-size: 16px; color: red'><b>系统级别错误,测试环境时用tp默认错误渲染</b></p>";
                return parent::render($e);
            }
            ExceptionEmun::throwException(SystemException::SPECIAL_ERROR);
        }
        return json($exception_info);
    }

    /**
     * 将异常写入日志
     * @param Exception $e
     */
    private function recordErrorLog(Exception $e)
    {
        $log = $e->getMessage() . "\n";
        $trace = $e->getTrace();
        $log .= sprintf("%s (%s) %s", $e->getFile(), $e->getLine(), "\n");
        foreach ($trace as $key => $value) {
            if (!empty($value['file']) && !empty($value['line'])) {
                $log .= sprintf("%s (%s) %s", $value['file'], $value['line'], "\n");
            }
        }
        Log::error($log);
    }

}
